package com.xydpeng.tech.order.service.order.impl;

import com.alibaba.cola.statemachine.StateMachine;
import com.alibaba.cola.statemachine.StateMachineFactory;
import com.xydpeng.tech.common.pojo.ComResult;
import com.xydpeng.tech.order.dal.das.OrderDas;
import com.xydpeng.tech.order.enums.OrderStatusEnum;
import com.xydpeng.tech.order.service.order.OrderService;
import com.xydpeng.tech.order.service.order.statemachine.OrderContext;
import com.xydpeng.tech.order.service.order.statemachine.OrderEvent;
import com.xydpeng.tech.order.service.order.statemachine.OrderStateMachineConfig;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2024/12/10
 * @description:
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDas orderDas;

    @Override
    public ComResult createOrder(Long orderCode) {
        return null;
    }

    @Override
    public ComResult payOrder(Long orderCode) {
        return null;
    }

    @Override
    public ComResult orderPaySucess(Long orderCode) {
        return null;
    }

    @Override
    public ComResult pushToOFS(Long orderCode) {
        return null;
    }

    @Override
    public ComResult receiveOrder(Long orderCode) {
        return null;
    }

    @Override
    public ComResult cancelOrder(Long orderCode) {
        return null;
    }

    // PAY, SHIP, DELIVER, CANCEL
    public ComResult fireEvent(Long orderCode, OrderEvent event) {
        StateMachine<OrderStatusEnum, OrderEvent, OrderContext> stateMachine = StateMachineFactory.get(OrderStateMachineConfig.MACHINE_ID);
        OrderStatusEnum sourceState = orderDas.getOrderStatus(orderCode);
        OrderContext orderContext = new OrderContext();
        int i = 0;
        while (stateMachine.verify(sourceState, OrderEvent.PAY)) {
            OrderStatusEnum orderStatus = stateMachine.fireEvent(OrderStatusEnum.PENDING, event, orderContext);
            //内部转移、条件不满足
            if (orderContext.isTransitSuccess()) {
                //记录日志
                log.info("");
                break;
            }
            sourceState = orderDas.getOrderStatus(orderCode);
            i++;
            if (i > 5) {
                log.warn("");
                break;
            }
        }
        return null;
    }


}
